package cn.itcast.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisConstant;
import cn.itcast.constant.StatusConstant;
import cn.itcast.exception.DeletionNotAllowedException;
import cn.itcast.mapper.DishFlavorMapper;
import cn.itcast.mapper.DishMapper;
import cn.itcast.mapper.SetmealDishMapper;
import cn.itcast.mapper.SetmealMapper;
import cn.itcast.result.PageBean;
import cn.itcast.service.DishService;
import cn.itheima.goods.dto.DishDTO;
import cn.itheima.goods.dto.DishPageQueryDTO;
import cn.itheima.goods.pojo.Dish;
import cn.itheima.goods.pojo.DishFlavor;
import cn.itheima.goods.vo.DishOverViewVO;
import cn.itheima.goods.vo.DishVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
@Slf4j
@AllArgsConstructor
public class DishServiceImpl implements DishService {

    private DishMapper dishMapper;
    private DishFlavorMapper dishFlavorMapper;
    private SetmealDishMapper setmealDishMapper;
    private SetmealMapper setmealMapper;
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品带口味子表
     *
     * @param dishDTO 菜品信息
     */
    @Override
    @Transactional
    public void addWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);

        //向菜品表插入1条数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);//后绪步骤实现
        }

        redisTemplate.delete(RedisConstant.DISH_LIST + dishDTO.getCategoryId());
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO 查询条件
     * @return 菜品分页列表
     */
    @Override
    public PageBean pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageBean(page.getTotal(), page.getResult());
    }

    /**
     * 菜品批量删除
     *
     * @param ids 要删除的id集合
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        List<Dish> dishes = dishMapper.getByIds(ids);
        if (!dishes.isEmpty()) {
            //当前菜品处于起售中，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (!setmealIds.isEmpty()) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的菜品数据
        dishMapper.deleteByIds(ids);//后绪步骤实现
        //删除菜品关联的口味数据
        dishFlavorMapper.deleteByDishIds(ids);//后绪步骤实现

        Set keys = redisTemplate.keys(RedisConstant.DISH_LIST + ".*");

        redisTemplate.delete(keys);
    }

    /**
     * 根据id查询菜品
     *
     * @param id 要查询的菜品id
     * @return 菜品信息
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);//后绪步骤实现

        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO 菜品信息
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //修改菜品表基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

        Set keys = redisTemplate.keys(RedisConstant.DISH_LIST + "*");

        redisTemplate.delete(keys);
    }

    /**
     * 菜品起售、停售
     *
     * @param status 状态
     * @param id     需要修改的菜品id
     */
    @Override
    public void updateStatus(Integer status, Long id) {

        if (Objects.equals(status, StatusConstant.DISABLE)) {
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(id);

            setmealIds.forEach(s -> {
                setmealMapper.updateStatus(StatusConstant.DISABLE, s);
            });
        }

        Set keys = redisTemplate.keys(RedisConstant.DISH_LIST + "*");

        redisTemplate.delete(keys);

        dishMapper.updateStatus(status, id);
    }

    /**
     * 根据分类id查询菜品列表
     *
     * @param categoryId 分类id
     * @return 无
     */
    @Override
    public List<DishVO> getListByCategoryId(Long categoryId) {
        return dishMapper.getListByCategoryId(categoryId);
    }

    /**
     * 根据菜品信息查询口味
     *
     * @param dish 菜品信息
     * @return 菜品详情
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {

        List<DishVO> dishVOS = (List<DishVO>) redisTemplate.opsForValue().get(RedisConstant.DISH_LIST + dish.getCategoryId());

        if (dishVOS != null) {
            return dishVOS;
        }

        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        redisTemplate.opsForValue().set(RedisConstant.DISH_LIST + dish.getCategoryId(), dishVOList);

        return dishVOList;
    }

    @Override
    public DishOverViewVO getCountByStatus() {
        return dishMapper.getCountByStatus();
    }
}
